package org.nf.trading.service.app.order.consumer;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.nf.trading.config.RabbitConfig;
import org.nf.trading.dao.OrderMapper;
import org.nf.trading.dao.ProductMapper;
import org.nf.trading.entity.Order;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@RequiredArgsConstructor
public class DelayOrderConsumer {
    private final OrderMapper orderMapper;

    private final ProductMapper productMapper;

    /**
     * 延迟消费，如果用户在指定的时间内未支付，那么将订单改为无效
     *
     * @param order
     */
    @RabbitListener(queues = RabbitConfig.DELAY_QUEUE_NAME)
    public void receiveMessage(Order order) {
        log.info("接收消息，订单编号：{}", order);
        //依据订单编号查询数据库
        order = orderMapper.selectByPrimaryKey(order.getOrderId());
        if (order.getOrderStatus() == 0) {
            order.setOrderStatus(3);
            orderMapper.updateByPrimaryKey(order);
            log.info("订单已取消");
            //回滚库存
            productMapper.rollbackStock(order.getProductId(), order.getProductCount());
        }
    }
}